from __future__ import annotations
from typing import Optional
from sqlalchemy.orm import Mapped, mapped_column, relationship
from extensions import db
from datetime import datetime, date

class Profit(db.Model):
    """利润模型"""
    __tablename__ = 'profits'

    # 利润记录ID，使用UUID格式作为唯一标识，用于系统间数据关联
    profit_id: Mapped[str] = mapped_column(db.String(36), primary_key=True)
    # 所属店铺ID，关联stores表，标识利润所属的店铺
    store_id: Mapped[str] = mapped_column(db.String(36), db.ForeignKey('stores.store_id'), nullable=False)
    # 利润金额，记录具体的利润数值
    amount: Mapped[float] = mapped_column(db.Float, nullable=False)
    # 利润类型，标识利润的来源类型，如：营业收入、服务费等
    type: Mapped[str] = mapped_column(db.String(20), nullable=False)
    # 利润日期，记录利润产生的具体日期
    date: Mapped[date] = mapped_column(db.Date, nullable=False)
    # 描述信息，存储利润相关的补充说明
    description: Mapped[Optional[str]] = mapped_column(db.Text)
    # 记录创建时间，利润记录首次创建的时间戳
    created_at: Mapped[datetime] = mapped_column(db.DateTime, default=datetime.utcnow)
    # 记录最后更新时间，利润记录最后一次修改的时间戳
    updated_at: Mapped[datetime] = mapped_column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    
    # 关系
    store = relationship('Store', foreign_keys=[store_id], backref=db.backref('profits', lazy='dynamic'))

    def __init__(self, profit_id: str, store_id: str, amount: float, type: str, 
                 date: date, description: Optional[str] = None) -> None:
        self.profit_id = profit_id
        self.store_id = store_id
        self.amount = amount
        self.type = type
        self.date = date
        self.description = description

    def to_dict(self) -> dict:
        """将模型转换为字典"""
        return {
            'profit_id': self.profit_id,
            'store_id': self.store_id,
            'amount': self.amount,
            'type': self.type,
            'date': self.date.isoformat() if self.date else None,
            'description': self.description,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'updated_at': self.updated_at.isoformat() if self.updated_at else None
        }